package com.oocl.servlet;

import static com.oocl.util.IPPropertiesUtil.getProperty;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.pojo.Constants;
import com.oocl.pojo.Merchant;
import com.oocl.pojo.Protocol;
import com.oocl.pojo.State;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.MerchantManagerFactory;
import com.oocl.util.DESUtil;
import com.oocl.util.HTTPConnUtil;

/**
 * Servlet implementation class HomeServlet
 */
@WebServlet("/sec/home")
public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String STATE_ADDREESS = String.format("http://%s:%s/O2OAdministrator/approvalResult?id=", getProperty("admin.ipaddr"), getProperty("admin.port"));
    private MerchantManager merchantManager=null;
    private DESUtil desUtil = null;
    public HomeServlet() {
        super();
        merchantManager = MerchantManagerFactory.getInstance();
        desUtil = new DESUtil();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Merchant merchant = (Merchant) session.getAttribute("merchant");
		if (merchant.getmStatus()!=Constants.APPLY_PASSED) {
			String result = HTTPConnUtil.sendGet(STATE_ADDREESS+desUtil.encrypt(merchant.getmId(), "UTF-8")+"&dd="+new Date().getTime());
			if (result==null) {
				request.getRequestDispatcher("../serverDown").forward(request, response);
			}
			Protocol protocol = new ObjectMapper().readValue(result, Protocol.class);
			if (protocol!=null) {
				LinkedHashMap<String, Object> stateMap = new LinkedHashMap<>();
				stateMap = (LinkedHashMap<String, Object>) protocol.getMsgObj();
				State stateFeedBack = new State((Integer)stateMap.get("state"), (String)stateMap.get("content"));
				if (stateFeedBack==null||stateFeedBack.getState()==-1) {
					stateFeedBack.setState(0);
				}
				if (stateFeedBack.getState()==2) {
					request.setAttribute("feedback", stateFeedBack.getContent());
				}
				merchant.setmStatus(stateFeedBack.getState());
				merchantManager.updateMerchant(merchant);
				
			}
		}
		session.setAttribute("merchant", merchant);
		request.getRequestDispatcher("/WEB-INF/views/home.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
